#include "incs.h"
#include "PhysWorld.h"

PhysWorld::PhysWorld() : mPhysWorld(0)
{
	// 120 is the phys framerate we want
	mUpdate = 1.0f / 120.0;
	mElapsed = 0;
}

void PhysWorld::DestroyPhysicsWorld()
{
	delete mPhysWorld;
}

void PhysWorld::CreatePhysicsWorld()
{
	mPhysWorld = new OgreNewt::World();
	mPhysWorld->setWorldSize(Ogre::AxisAlignedBox(-10000, -10000, -10000,
		+10000, +10000, +10000));
}


OgreNewt::World * PhysWorld::GetPhysWorld()
{
	return mPhysWorld;
}

void PhysWorld::InitializePhysicsDebugger( Ogre::SceneManager * mgr )
{
	OgreNewt::Debugger::getSingleton().init(mgr);
}

void PhysWorld::UpdatePhysicsWorld( Ogre::Real const & elapsedSinceLastFrame )
{
	assert(mPhysWorld);

	mElapsed += elapsedSinceLastFrame;

	int count = 0;

	// loop through and update as many times as necessary (up to 10 times maximum).
	if ((mElapsed > mUpdate) && (mElapsed < (mUpdate * 10)) )
	{
		while (mElapsed > mUpdate)
		{
			GetPhysWorld()->update( mUpdate );
			mElapsed -= mUpdate;
			count++;
		}
	}
	else
	{
		if (mElapsed < (mUpdate))
		{
			// not enough time has passed this loop, so ignore for now.
		}
		else
		{
			// too much time has passed (would require more than 10 updates!), so just update once and reset.
			// this often happens on the first frame of a game, where assets and other things were loading, then
			// the elapsed time since the last drawn frame is very long.
			mPhysWorld->update( mElapsed );
			count++;
			mElapsed = 0.0f; // reset the elapsed time so we don't become "eternally behind".
		}
	}
}